""" TestRecord module """
import os
import zlib
import pickle
import io
from PyQt4.QtGui import QMessageBox
from PyQt4.QtCore import QObject, QDate
from PsyBlockGame.Game import validate

RESULT_SUCCESS              = 0
RESULT_FAILED_TIMEOUT       = 1
RESULT_FAILED_WRONG         = 2
RESULT_FAILED_BEFORE_START  = 3
RESULT_INTERRUPTED          = 99

RECORDS_SAVE = r".\data\records.dat"

class TestRecord:
    def __init__(self, user = "<Unknown>"):
        self.user  = user
        self.tests = []
        self.preset = ""
        self.updateDate()

    def updateDate(self):
        today = QDate().currentDate()
        self.date = (today.day(), today.month(), today.year())

    def __lt__(self, p):
        d, m, y = self.date
        pd, pm, py = p.date

        if y != py:
            return y < py
        if m != pm:
            return m < pm

        return d < pd

    def validate(self):
        validate(self)

    def addResultTimeout(self):
        self.tests.append((RESULT_FAILED_TIMEOUT, None))

    def addResultWrong(self, time):
        self.tests.append((RESULT_FAILED_WRONG, time))

    def addResultSuccess(self, time):
        self.tests.append((RESULT_SUCCESS, time))

    def addResultBeforeStart(self):
        self.tests.append((RESULT_FAILED_BEFORE_START, None))
        
    def addResultInterrupted(self):
        self.tests.append((RESULT_INTERRUPTED, None))

class RecordBase(QObject):
    def __init__(self):
        super(RecordBase, self).__init__()
        self.records = []

    def addRecord(self, p, presetName):
        p.updateDate()
        p.preset = presetName
        self.records.append(p)

    def save(self):
        stream = io.BytesIO()
        stream.write(pickle.dumps(self.records))
        bin = zlib.compress(stream.getvalue())

        try:
            f = open(RECORDS_SAVE, "wb")
            f.write(bin)
            f.close()
        except:
            QMessageBox.critical(None, self.tr("Cannot save record results"), self.tr("Cannot open file '%s' for writing") % RECORDS_SAVE)

    def load(self):
        if not os.access(RECORDS_SAVE, os.F_OK):
            return

        try:
            f = open(RECORDS_SAVE, "rb")
            bin = f.read()
            f.close()
        except:
            QMessageBox.warning(None, self.tr("Failed to load records"), self.tr("Cannot open file '%s' for reading") % RECORDS_SAVE)
            return

        data = zlib.decompress(bin)
        self.records = pickle.loads(data)

        for p in self.records:
            p.validate()
